﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

namespace WEALTH.Manager.Customer
{
    public partial class PDFManager : BasePage
    {
        private ExcuteDao dao = new ExcuteDao();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["UrlType"] != null && Request.QueryString["UrlType"].Equals("menu"))
            {
                Session["SortExpression_PdfList"] = null;
                Session["SortDirection_PdfList"] = null;
                Session["txtpdfname"] = null;
            }
            if (!string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
            {
                string pageIndex = Request.QueryString["pageIndex"];
                int index = Convert.ToInt32(pageIndex);
                gvPdf.PageIndex = index;

                Session["PdfListIndex"] = index;

                setSessionData();
            }
            //设置分页状态
            if (Session["SortExpression_PdfList"] != null)
            {
                this.gvPdf.Attributes["SortExpression_PdfList"] = Session["SortExpression_PdfList"].ToString();
                this.gvPdf.Attributes["SortDirection_PdfList"] = Session["SortDirection_PdfList"].ToString();
                setSortColumnStyle(this.gvPdf, Session["SortExpression_PdfList"].ToString(), Session["SortDirection_PdfList"].ToString());
            }
            //setSortColumnStyle(gvPdf, this.gvPdf.Attributes["SortExpression_PdfList"].ToString(),
            //     this.gvPdf.Attributes["SortDirection_PdfList"].ToString());
            if (!IsPostBack)
            {
                ViewState["PdfAll"] = dao.Get_PdfListALL(SpecialCharHandler.HtmlEncode(txtpdfname.Text));

                //初次加载清空分页状态
                //if (string.IsNullOrEmpty(Request.QueryString["pageIndex"]) && Session["UrlType"] == null)
                //{
                //    Session["SortExpression_PdfList"] = null;
                //    Session["SortDirection_PdfList"] = null;
                //}
                SearchPdfBindData();
            }
        }
        private void setSessionData()
        {
            //检索条件记录
            if (Session["txtpdfname"] != null)
            {
                txtpdfname.Text = SpecialCharHandler.HtmlDiscode(Session["txtpdfname"].ToString());
            }
            if (Session["PdfListIndex"] != null)
            {
                gvPdf.PageIndex = (int)Session["PdfListIndex"];
            }
        }
        #region 信息列表事件

        /// <summary>
        /// 信息列表数据加载时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvPdf_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("id", e.Row.RowIndex.ToString());
                e.Row.Attributes.Add("onKeyDown", "SelectRow();");
                e.Row.Attributes.Add("onClick", "MarkRow(" + e.Row.RowIndex.ToString() + ");");
                ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "../Customer/DownloadPdf.aspx?Pdfname="
                    + SpecialCharHandler.HtmlDiscode(((HyperLink)e.Row.Cells[1].Controls[0]).Text).Replace("&", "amp;");

            }
        }
        #endregion

        /// <summary>
        /// 搜索按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ViewState.Clear();
            ViewState["PdfAll"] = dao.Get_PdfListALL(SpecialCharHandler.HtmlEncode(txtpdfname.Text));
            //清空分页状态
            Session["SortExpression_PdfList"] = null;
            Session["SortDirection_PdfList"] = null;

            //检索条件记录
            Session["txtpdfname"] = SpecialCharHandler.HtmlEncode(txtpdfname.Text);

            SearchPdfBindData();
        }

        /// <summary>
        /// 选择页面功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvPdf_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvPdf.PageIndex = e.NewPageIndex;
            pageIndex = e.NewPageIndex;
            Session["PdfListIndex"] = pageIndex;
            SearchPdfBindData();
        }

        /// <summary>
        /// GridView排序事件
        /// </summary>
        protected void gvPdf_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string SortExpression_PdfList = e.SortExpression.ToString();
            //// 假定为排序方向为“顺序”
            string SortDirection_PdfList = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (SortExpression_PdfList == this.gvPdf.Attributes["SortExpression_PdfList"])
            {
                //获得下一次的排序状态
                SortDirection_PdfList = (this.gvPdf.Attributes["SortDirection_PdfList"].ToString() == SortDirection_PdfList ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.gvPdf.Attributes["SortExpression_PdfList"] = SortExpression_PdfList;
            this.gvPdf.Attributes["SortDirection_PdfList"] = SortDirection_PdfList;
            //记录分页状态
            Session["SortExpression_PdfList"] = SortExpression_PdfList;
            Session["SortDirection_PdfList"] = SortDirection_PdfList;

            setSortColumnStyle(this.gvPdf, SortExpression_PdfList, SortDirection_PdfList);
            this.SearchPdfBindData();
        }

        /// <summary>
        /// 绑定到GridView
        /// </summary>
        private void SearchPdfBindData()
        {
            // 获取GridView排序数据列及排序方向
            string SortExpression_PdfList = this.gvPdf.Attributes["SortExpression_PdfList"];
            string SortDirection_PdfList = this.gvPdf.Attributes["SortDirection_PdfList"];
            // 调用业务数据获取方法
            DataTable dtBind = (DataTable)ViewState["PdfAll"];

            //页面数据总数
            recordCount = dtBind.Rows.Count;

            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(SortExpression_PdfList)) && (!string.IsNullOrEmpty(SortDirection_PdfList)))
            {
                dtBind.DefaultView.Sort = string.Format("{0} {1}", SortExpression_PdfList, SortDirection_PdfList);
            }
            // GridView绑定并显示数据
            this.gvPdf.DataSource = dtBind;
            this.gvPdf.DataBind();

            pageCount = gvPdf.PageCount;
            pageIndex = gvPdf.PageIndex;

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {

                int isok = 0;

                bool ischecked = false;
                for (int i = 0; i <= gvPdf.Rows.Count - 1; i++)
                {
                    CheckBox CheckBox = (CheckBox)gvPdf.Rows[i].FindControl("chkdelete");
                    if (CheckBox.Checked == true)
                    {
                        if (delPdf(((HyperLink)gvPdf.Rows[i].Cells[1].Controls[0]).Text))
                        {
                            string Pdfid = gvPdf.Rows[i].Cells[0].Text;
                            isok = dao.Delete_Pdf(Convert.ToInt32(Pdfid));

                            ischecked = true;
                        }
                    }

                }
                if (ischecked)
                {
                    ischecked = false;
                    if (isok == -1)
                    {
                        ShowMsg("删除PDF成功！", 0);
                        ViewState["PdfAll"] = dao.Get_PdfListALL(SpecialCharHandler.HtmlEncode(txtpdfname.Text));
                        SearchPdfBindData();
                    }
                    else
                    {
                        ShowMsg("删除PDF失败！", 1);
                    }
                }
            }
            catch (Exception ex)
            {
                AppFunction.SaveExceptionLog(ex);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (CheckFile(FileUpload1))
            {
                int isok = 0;
                if (uploadPdf())
                {
                    isok = dao.Insert_PDF(FileUpload1.FileName, getCurrentUser().UserID);
                }
                if (isok != 0)
                {                    
                    ViewState["PdfAll"] = dao.Get_PdfListALL("");
                    SearchPdfBindData();
                    ShowMsg("上传文件成功", 0);
                }
                else
                {
                    ShowMsg("无上传文件或上传失败，请确认！", 1);
                }
            }
        }

        private bool CheckFile(FileUpload fileupload)
        {
            if (!fileupload.HasFile)
            {
                return false;
            }
            string fileleixing = System.IO.Path.GetExtension(fileupload.FileName).ToLower(); //获取文件的扩展名
            if (fileleixing != ".pdf")
            {
                ShowMsg("文件类型不一致,请确认是PDF文件！", 1);
                return false;
            }
            else
            {
                int fileLenth = fileupload.PostedFile.ContentLength / 1024;
                if (fileLenth > 10240)
                {
                    ShowMsg("文件大小不能超过10MB", 1);
                    return false;
                }
            }
            return true;
        }
        private bool delPdf(string filename)
        {            
            if (!File.Exists(HttpContext.Current.Request.PhysicalApplicationPath + "PDF//" + filename))
            {
                return false;
            }
            File.Delete(HttpContext.Current.Request.PhysicalApplicationPath + "PDF//" + filename);
            return true;
        }
        private bool uploadPdf()
        {
            try
            {
                //检测一下FileUpload1是否选择了上传文件
                if (FileUpload1.HasFile)
                {
                    //检测一下目录是否存在
                    if (!Directory.Exists(HttpContext.Current.Request.PhysicalApplicationPath + "PDF//"))
                    {
                        Directory.CreateDirectory(HttpContext.Current.Request.PhysicalApplicationPath + "PDF//");
                    }
                    string savePath = @"\PDF\";
                    if (FileUpload1.HasFile)
                    {
                        savePath += FileUpload1.FileName;
                    }
                    if (!File.Exists(HttpContext.Current.Request.PhysicalApplicationPath + "PDF//" + FileUpload1.FileName))
                    {
                        //string AutoName =System.IO.Path.GetExtension(FileUpload1.FileName).ToString();
                        string temppath = Server.MapPath("~/") + @"\PDF\" + FileUpload1.FileName;
                        //string path = Server.MapPath("~/") + @"\PDF\" + AutoName;
                        FileUpload1.PostedFile.SaveAs(temppath);
                        Response.Clear();
                        return true;
                    }
                    else
                    {
                         ShowMsg( FileUpload1.FileName + "文件已经存在,重新上传文件!",1);
                         return false;
                    }
                }
                else
                {
                    ShowMsg("请选择上传文件!", 1);
                    return false;
                }
            }
            catch (Exception ex)
            {
                
                string msg = ex.Message.ToString();
                AppFunction.SaveExceptionLog(ex);
                return false;
            }
        }
    }
}
